<template>
  <v-chart
    :style="style"
    :option="widget.option"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>
<script>
import _ from "lodash";
import { renderWidgetData } from "../tools/DataUtils";
export default {
  props: {
    widget: {
      type: [Object],
      default: () => {},
    },
  },
  data() {
    return {
      render: null,
    };
  },
  computed: {
    style() {
      return {
        width: this.widget.location.width + "px",
        height: this.widget.location.height + "px",
      };
    },
    option() {
      return {
        barWidth: this.widget.option.series[0].barWidth,
        itemStyle: this.widget.option.series[0].itemStyle,
      };
    },
    data() {
      return this.widget.data;
    },
    refresh() {
      return this.widget.service.timestamp;
    },
  },
  watch: {
    option: {
      handler(val) {
        for (let i = 1; i < this.widget.option.series.length; i++) {
          this.widget.option.series[i].barWidth = val.barWidth;
          this.widget.option.series[i].itemStyle = _.cloneDeep(val.itemStyle);
        }
      },
      deep: true,
    },
    data: {
      handler() {
        this.refreshWidgetInfo();
      },
      deep: true,
    },
    refresh: {
      handler() {
        this.refreshWidgetInfo();
      },
    },
  },
  mounted() {
    this.refreshWidgetInfo();
  },
  destroyed() {
    this.recoveryRenderObject();
  },
  methods: {
    refreshWidgetInfo() {
      this.recoveryRenderObject();
      this.render = renderWidgetData(this.widget, this.renderEchartInfo);
    },
    renderEchartInfo(data) {
      const option = this.widget.option;
      option.xAxis.data = data.categories;
      // 每次刷新都只保留一个Series元素，其他的删掉
      option.series.splice(1, option.series.length - 1);
      for (let i = 0; i < data.series.length; i++) {
        let chartData = data.series[i];
        let item = option.series[i];
        if (!item) {
          // 如果数据长度大于配置长度，则深拷贝一个配置出来
          option.series.push(_.cloneDeep(option.series[0]));
          item = option.series[i];
        }
        item.name = chartData.name;
        item.data = chartData.data;
      }
    },
    recoveryRenderObject() {
      if (this.render && this.render.apiTimer) {
        clearInterval(this.render.apiTimer);
        this.render.apiTimer = null;
      }
      if(this.render && this.render.websocket) {
        this.render.websocket.doDisconnect();
      }
    },
  },
};
</script>